package top.codedance.iotp.common.util;

public class Ascii2HexUtil {
    /**
     * ASCII 转 HEX
     * @param str
     * @return
     */
    public static String ascii2hex(String str){
        char[] chars = str.toCharArray();
        StringBuilder hex = new StringBuilder();
        for (char aChar : chars){
            hex.append(Integer.toHexString((int) aChar));
        }
        return hex.toString();
    }

    /**
     * hex 转 ASCII
     * @param hex
     * @return
     */
    public static String hex2ascii(String hex){
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        for (int i=0;i<hex.length()-1; i+=2){
            String output = hex.substring(i, (i + 2));
            int decimal = Integer.parseInt(output, 16);
            sb.append((char)decimal);
            temp.append(decimal);
        }
        return sb.toString();
    }

    /**
     * 调用示例
     * @param args
     */
    public static void main(String[] args){
        String in = "hello";
        String out = ascii2hex(in);
        System.out.println(out);
        String result = hex2ascii(out);
        System.out.println(result);
    }
}
